The Visitor design pattern represents an operation to be performed on the elements of an object structure. This pattern lets you define a new operation (ObjectStructure) without changing the classes of the elements on which it operates.
簡單來說~ 此模式讓你能定義一個新的操作來訪問對象結構~ 無須動到原本的結構~
學習目標: 訪問者模式的概念及實務
學習難度: ☆☆☆
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
//為對象結構中的每個 ConcreteElement 類聲明一個訪問操作。
public abstract class Visitor
{
public abstract void VisitConcreteProductA(ProductA concreteProductA);
}
//實現訪問者聲明的每個操作。每個操作都實現了為結構中的相應類或對象定義的算法片段。
public class ConcreteVisitor1 : Visitor
{
public override void VisitConcreteProductA(ProductA concreteProductA)
{
Console.WriteLine(concretePlayerA.GetType().Name + " visited by "+this.GetType().Name);
}
}
//定義一個以訪問者為參數的 Accept 操作
public abstract class Product
{
public abstract void Accept(Visitor visitor);
}
//實現以訪問者為參數的 Accept 操作
public class ProductA : Product
{
public override void Accept(Visitor visitor)
{
visitor.VisitConcreteProductA(this);
}
}
//可以提供高級界面以允許訪問者訪問其元素,例如列表或集合
public class ProductManager
{
List<Product> products = new List<Product>();
public void Attach(Product product)
{
products.Add(product);
}
public void Detach(Product product)
{
products.Remove(product);
}
public void Accept(Visitor visitor)
{
foreach (Product product in products)
{
product.Accept(visitor);
}
}
}
public class MainProgram
{
public static void Main(string[] args)
{
ProductManager productManager = new ProductManager();
Product productA = new ProductA();
productManager.Attach(productA);
ConcreteVisitor1 visitor1 = new ConcreteVisitor1();
productManager.Accept(visitor1);
}
}
}
參考資料:
https://www.dofactory.com/net/visitor-design-pattern